package com.region.spring.operator;

import com.region.common.adapter.logging.LoggerAdapter;
import com.region.common.adapter.logging.LoggerAdapterFactory;
import com.region.core.env.PropertiesOperator;
import com.region.core.env.PropertySourceLocator;
import com.region.core.env.listener.PropertyRefreshListener;
import com.region.core.exception.NoPropertySourceException;
import org.springframework.core.env.Environment;

import java.util.Map;

/**
 * @author liujieyu
 * @date 2024/7/22 19:43
 * @desciption
 */
public class RegionSpringPropertiesOperator implements PropertiesOperator {

    private static final LoggerAdapter loggerAdapter = LoggerAdapterFactory.getLogger(RegionSpringPropertiesOperator.class);

    private PropertiesOperator delegate;

    private Environment environment;

    public RegionSpringPropertiesOperator(PropertiesOperator delegate) {
        this.delegate = delegate;
    }

    public void setEnvironment(Environment environment) {
        this.environment = environment;
    }

    @Override
    public void addPath(String path) {
        this.delegate.addPath(path);
    }

    @Override
    public void addLocator(PropertySourceLocator locator) {
        this.delegate.addLocator(locator);
    }

    @Override
    public void addRefreshListener(PropertyRefreshListener listener) {
        this.delegate.addRefreshListener(listener);
    }

    @Override
    public Object get(String keyName) {
        String property = environment.getProperty(keyName);
        if (property == null) {
            return this.delegate.get(keyName);
        }
        return property;
    }

    @Override
    public Object get(String keyName, Object defaultValue) {
        String property = environment.getProperty(keyName, String.valueOf(defaultValue));
        if (property == null) {
            return this.delegate.get(keyName, defaultValue);
        }
        return property;
    }

    @Override
    public void refresh(String keyName, Object newValue) {
        try {
            this.delegate.refresh(keyName, newValue);
        } catch (Exception e) {
            if (e instanceof NoPropertySourceException && environment.containsProperty(keyName)) {
                // explain key not found in default properties, but in environment of spring
                loggerAdapter.warn("Due to key[" + keyName + "] not found in default properties, but in environment of spring.");
            } else {
                throw e;
            }
        }
    }

    @Override
    public void load(Map<Object, Object> properties) {
        this.delegate.load(properties);
    }
}
